﻿using System;
using System.Linq;
using System.Web.Mvc;
using Home.Site.Models.DataLayer;

namespace Home.Site.Controllers
{
    public class TagController : Controller
    {
        private readonly IReviewTagRepository reviewTagRepository;
        private readonly ITagRepository tagRepository;

        public TagController(ITagRepository tagRepository, IReviewTagRepository reviewTagRepository)
        {
            this.tagRepository = tagRepository;
            this.reviewTagRepository = reviewTagRepository;
        }

        public ActionResult Index()
        {
            return View("Tag/_Index",tagRepository.All);
        }

        public ActionResult Create()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(string name, int id)
        {
            var isExistR = reviewTagRepository.All.Any(r => r.ReviewId == id && r.TagName1.name == name);
            if (!isExistR)
            {
                if (tagRepository.Find(name) == null)
                {
                    var tag = new TagName { name = name };
                    tagRepository.Insert(tag);
                }
                var tagReview = new ReviewTag
                    {
                        ReviewId = id,
                        TagName = name
                    };
                reviewTagRepository.Insert(tagReview);
                return Json(name);
            }
            return null;
        }

        [HttpGet]
        public JsonResult GetTags(string term)
        {
            try
            {
                term = term.ToLower();
                var possibles =
                    tagRepository.All.Where(l => l.name.Contains(term)).Select(l => l.name).Distinct().
                        Select(x => new
                        {
                            name = x,
                            alias = x
                        });

                return new JsonResult
                {
                    ContentType = "text/plain",
                    Data = new
                    {
                        term,
                        total = possibles.Count(),
                        suggestions = possibles.Select(p => p.alias).ToArray(),
                        matches = possibles,
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            catch (Exception)
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            var tagname = tagRepository.Find(id);
            tagRepository.Delete(tagname);
            return RedirectToAction("Index", "Tag");
        }
    }
}